#!-*- encoding:utf8 -*-
from django.template import Template, Context, RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.contrib.auth.decorators import user_passes_test, login_required
#from mysite.contact.forms import ContactForm
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger
from newosmp import settings
from django.db.models import  Sum, Q

from newosmp.util import commom
from newosmp.monitor.models import Monitor
from newosmp.strategy.models import Strategy
from newosmp.host.models import Host, Product, IDC, HostModel
from newosmp.group.models import Group
from newosmp.alert.models import AlertBing, AlertReceive
import datetime
import xmlrpclib
import json,urllib



#可以使用 assert False 作为断点调试

def index(request):
    page = int(request.GET.get('page', '1'))
    host = Host.objects.all()
    #分页
    num = settings.PAGE
    count = host.count() 
    (host_list, page_list, page_num) = commom.pagination(host, page, num)
    (page_up, page_down) = commom.getPage(page, page_num) #上下页

    #树
    auth_pids = request.session['auth_pids']
    
    tree = ""
    tree = commom.creatree(-1, tree, '', '/host/detail?id=', auth_pids=auth_pids)
#    print tree
    request.session['tree'] = tree
    
    idcs = IDC.objects.all()
    return render_to_response("host.html", locals())

def detail(request):
    id = request.GET.get('id', '')
    host_info = Host.objects.get(id=id)
    host_model = host_info.mid
    obj = Monitor.objects.filter(hid=host_info, tpl='host')
    if len(obj) > 0:
       host_monitor = obj[0]
       table = host_monitor.table
       host_bing = AlertBing.objects.filter(mid=host_monitor)[0]

    
    monitor = Monitor.objects.filter(hid=id).exclude(tpl='host')

    # GroupIDList
    gil = []
    for m in monitor:
        ab = AlertBing.objects.filter(mid=m)
        for a in ab:
            gil.append(a.gid.id)

    recv = Group.objects.filter(id__in=gil)

    for m in monitor:
        if m.status == 'T':
            m.status = "正常"
        else:
            m.status = "异常"
        m.id = 1
        
    tree = request.session['tree']
    return render_to_response('hostdetail.html', locals())


def idc(request):
    id = request.GET.get('id')
    idc = IDC.objects.get(id=id)
    host_total = idc.num
    host_error = Host.objects.filter(idc=idc, status='F').count()
    host_normal = host_total - host_error
    host_cores = 1
    host_load = 0
    hosts = Host.objects.annotate(idc=idc, load=Sum('r_load'), cores=Sum('r_cpu_core'))
    if len(hosts) > 0:
        host_cores = hosts[0].cores
        host_load = hosts[0].load
    if host_cores < 0:
        idc_usage = "0.00"
    else:
        idc_usage = "%.2f" % (float(host_load) * 100 / host_cores) 
    if host_total == 0:
       idc_avail = "%.2f" % 100
    else:
        idc_avail = "%.2f" % (float(host_normal) * 100 / host_total)
    host_list = Host.objects.filter(idc=idc)
    print host_list
    return render_to_response("idcdetail.html", locals())

def search(request):
    key = request.POST.get('key', '')
    if key:
        q = Q(name__contains=key) | Q(ip__contains=key)
        host_list = Host.objects.filter(q)
        return render_to_response('host.html', locals())
    else:
        return render_to_response('host.html', locals())
 


def getinfo(request):
    host = request.GET.get('host', '')
    flag = request.GET.get('flag', 0)
    info = getRPCInfo(host, int(flag))
    return HttpResponse(json.dumps(info))


#主机增删改查
def add(request):
    """
    添加主机，添加完成后可进行克隆操作。
    """
    errors = []
    if request.method == 'POST':

        idc = IDC.objects.get(id=int(request.POST.get('idc')))
        ip = request.POST.get('ip').encode('utf-8')
        name = request.POST.get('hostname').encode('utf-8')
        lst = request.POST.get('setup_time').split("-")
        setup_time = datetime.date(int(lst[0]), int(lst[1]), int(lst[2]))
        model = HostModel.objects.get(id=int(request.POST.get('model')))
        pid = Product.objects.get(id=int(request.POST.get('product')))

        stra = Strategy.objects.get(id=int(request.POST.get('stra')))
        group = Group.objects.get(id=int(request.POST.get('group')))

        #创建主机
        host = Host.objects.create(idc=idc, ip=ip, name=name, status="T", \
                            setup_time=setup_time, mid=model, pid=pid)
        host.save()
        #机房计算
        idc.num += 1
        idc.save()
        ret = "create host ok\n"
        
        #创建监控
        tablename = "data_" + ip.replace(".", "_")
        m = Monitor.objects.create(name="host_%s" % ip, url="host://%s" % ip,
                    tpl="host", freq=60, open="T", status="T", table=tablename,
                    pid=pid, hid=host)
        m.save()
        ret += "create monitor ok \n"
        #创建表
        commom.createTplTable(tablename, "host")
        ret += "create table ok\n"
        #创建报警策略
        alert = AlertBing.objects.create(mid=m, sid=stra, gid=group)
        alert.save()
        #通知监控端
        noticeDaemon("start", m.id)
        ret += "create alert ok\n"
        tree = request.session['tree']
        return HttpResponseRedirect("/host/detail/?id=%s" % host.id)  
    else:
        #无操作进入时 - 数据初始化
        idcs = IDC.objects.all()
        products = Product.objects.filter(has_host = 'T')
        stra = Strategy.objects.filter(tpl="host")
        models = HostModel.objects.all()
        group = Group.objects.all()
        tree = request.session['tree']
        return render_to_response('hostadd.html', locals())

def modify(request):
    if request.method == 'POST':

        hid = int(request.POST.get('id'))
        idc = IDC.objects.get(id=int(request.POST.get('idc')))
        name = request.POST.get('hostname').encode('utf-8')
        lst = request.POST.get('setup_time').split("-")
        setup_time = datetime.date(int(lst[0]), int(lst[1]), int(lst[2]))
        model = HostModel.objects.get(id=int(request.POST.get('model')))
        pid = Product.objects.get(id=int(request.POST.get('product')))

        stra = Strategy.objects.get(id=int(request.POST.get('stra')))
        group = Group.objects.get(id=int(request.POST.get('group')))

        #修改主机
        host = Host.objects.get(id=hid)
        host.idc = idc
        host.name = name
        host.setup_time = setup_time
        host.mid = model
        host.pid = pid
        host.save()

        monitor = Monitor.objects.filter(hid=host, tpl="host")[0]
        hostalert = AlertBing.objects.filter(mid=monitor)[0]
        hostalert.sid = stra
        hostalert.gid = group
        hostalert.save()
        tree = request.session['tree']
        return HttpResponseRedirect("/host/detail/?id=%s" % host.id)  
    else:
        try:
            id = request.GET.get('id')
            host = Host.objects.get(id=id)
            idcs = IDC.objects.all()
            products = Product.objects.filter(has_host = 'T')
            stra = Strategy.objects.filter(tpl="host")
            models = HostModel.objects.all()
            group = Group.objects.all()

            #获取监控
            monitor = Monitor.objects.filter(hid=host, tpl="host")[0]
            hostalert = AlertBing.objects.filter(mid=monitor)[0]
            print hostalert
        except:
            pass
        tree = request.session['tree']
        return render_to_response('hostmodify.html', locals())

def remove(request):
    hid = request.GET.get('id',)
    host = Host.objects.get(id=hid)
    
    #机房计算
    idc = host.idc 
    idc.num -= 1
    idc.save()
    m = Monitor.objects.filter(hid=host, tpl="host")[0]
    #删除监控
    noticeDaemon("stop", m.id)
    host.delete()
    return HttpResponse(json.dumps({'flag': "SUCC"}))


def ajaxGetModel(request):
    id = request.GET.get('id', "")
    model = HostModel.objects.get(id=int(id))
    return render_to_response("ajaxhostmodel.html", locals())

def ajaxGetStra(request):
    id = request.GET.get('id', "")
    stra = Strategy.objects.get(id=int(id))
    dct = commom.str2dct(stra.value)
    cpu = dct.get('cpu', "-1|-1").split('|')
    mem = dct.get('mem', "-1|-1").split('|')
    disk = dct.get('disk', "-1|-1").split('|')
    net = dct.get('net', "-1|-1").split('|')
    load = dct.get('load', "-1|-1").split('|')

    return render_to_response("ajaxhoststra.html", locals())

def ajaxGetGroup(request):
    id = request.GET.get('id', "")
    group = Group.objects.get(id=int(id))
    people = User.objects.filter(id__in=group.user.split(','))
    print people
    return render_to_response("ajaxhostgroup.html", locals())


def edit(request):
    
    return HttpResponse("hostedit")

def list(request):
    hlist = Host.objects.all()
    #    render_to_response(list)
    print hlist
    return HttpResponse("hostlist")


def filter(request):
    """
    Ajax
    """
    id = request.POST.get('id', '') #机房ID
    hrlist = Host.objects.filter(idc=id)
    print hrlist
    '''返回该机房列表'''
    return HttpResponse("hostfilter")

       
#    return render_to_response("allflowlist.html",locals())


#主机克隆
def clone(request):
    if request.method == 'POST':
        host = Host.objects.get(id=int(request.POST.get('id')))
        monitor = Monitor.objects.filter(hid=host, tpl="host")[0]
        hostalert = AlertBing.objects.filter(mid=monitor)[0]
        cname = request.POST.getlist('cname')
        cip = request.POST.getlist('cip')
        
        i = 0
        while i < len(cip):
            name = cname[i]
            ip = cip[i]
            print ip
            newhost = Host.objects.create(idc=host.idc, ip=ip, name=name, status="T", \
                            setup_time=host.setup_time, mid=host.mid, pid=host.pid)
            newhost.save()
            #机房计算
            host.idc.num += 1
            host.idc.save()
        
            #创建监控
            tablename = "data_" + ip.replace(".", "_")
            m = Monitor.objects.create(name="host_%s" % ip, url="host://%s" % ip,
                    tpl="host", freq=60, open="T", status="T", table=tablename,
                    pid=newhost.pid, hid=newhost)
            m.save()

            #创建表
            commom.createTplTable(tablename, "host")
            #创建报警策略
            alert = AlertBing.objects.create(mid=m, sid=hostalert.sid, gid=hostalert.gid)
            alert.save()
            #通知监控端
            noticeDaemon("start", m.id)
            i += 1
        tree = request.session['tree']
        return HttpResponseRedirect("/host")  

    else:
        try:
            id = request.GET.get('id')
            host = Host.objects.get(id=id)
            idcs = IDC.objects.all()
            products = Product.objects.filter(has_host = "T")
            stra = Strategy.objects.filter(tpl="host")
            models = HostModel.objects.all()
            group = Group.objects.all()

            #获取监控
            monitor = Monitor.objects.filter(hid=host, tpl="host")[0]
            hostalert = AlertBing.objects.filter(mid=monitor)[0]
            print hostalert
        except:
            pass
        tree = request.session['tree']
        return render_to_response('hostclone.html', locals())


#机房
def room(request):
    pass


def noticeDaemon(do, id):
    #start, stop, reload
    try:
        url = "%s/%s/%d" % (settings.DaemonUrl, do ,id)
        print url
        fd = urllib.urlopen(url)
        data = fd.read()
        fd.close()
        return True
    except:
        return False
